﻿
Imports osi.root.connector
Imports osi.root.event
Imports osi.root.formation
Imports osi.root.lock
Imports osi.root.procedure
Imports osi.root.utils

Public Class async_pool_one_adapter(Of T)
    Inherits pool_one_adapter(Of T, iasync_device_pool(Of T))
    Private ReadOnly finish_get_event As signal_event
    Private begin_get_event As singleentry

    Public Sub New(ByVal p As iasync_device_pool(Of T))
        MyBase.New(p)
        finish_get_event = New signal_event()
    End Sub

    Protected Overloads Function [get](ByVal result As pointer(Of T)) As event_comb
        Dim ec As event_comb = Nothing
        Return New event_comb(Function() As Boolean
                                  Dim ins As T = Nothing
                                  ins = [get]()
                                  If ins Is Nothing Then
                                      finish_get_event.unmark()
                                      If begin_get_event.mark_in_use() Then
                                          result.renew()
                                          ins = [get]()
                                          If ins Is Nothing Then
                                              ec = p.get(result)
                                              Return waitfor(ec) AndAlso
                                                     goto_next()
                                          Else
                                              Return eva(result, ins) AndAlso
                                                     goto_next()
                                          End If
                                      Else
                                          Return waitfor(finish_get_event)
                                      End If
                                  Else
                                      Return eva(result, ins) AndAlso
                                             goto_end()
                                  End If
                              End Function,
                              Function() As Boolean
                                  If ec.end_result_or_null() AndAlso
                                     Not (+result) Is Nothing Then
                                      [set](+result)
                                      begin_get_event.release()
                                      finish_get_event.mark()
                                      Return goto_end()
                                  Else
                                      Return False
                                  End If
                              End Function)
    End Function
End Class
